package com.novel.controller;

import com.novel.domain.TableInfo;
import com.novel.framework.annotation.Log;
import com.novel.framework.base.BaseController;
import com.novel.framework.enums.BusinessType;
import com.novel.framework.web.page.TableDataInfo;
import com.novel.service.IGenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 代码生成 操作处理
 *
 * @author novel
 * @date 2020/3/25
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
    private final IGenService genService;

    public GenController(IGenService genService) {
        this.genService = genService;
    }

    /**
     * 获取数据表信息
     *
     * @param tableInfo 查询条件
     * @return 表信息
     */
    @RequiresPermissions("tool:gen:list")
    @GetMapping("/list")
    public TableDataInfo list(TableInfo tableInfo) {
        startPage();
        List<TableInfo> list = genService.selectTableList(tableInfo);
        return getDataTable(list);
    }

    /**
     * 生成代码
     *
     * @param response  response
     * @param tableName 表名
     * @throws IOException io异常
     */
    @RequiresPermissions("tool:gen:code")
    @Log(title = "系统工具", businessType = BusinessType.GEN_CODE)
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genService.generatorCode(tableName);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"novel.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 批量生成代码
     *
     * @param response   response
     * @param tableNames 表名数组
     * @throws IOException io异常
     */
    @RequiresPermissions("tool:gen:code")
    @Log(title = "系统工具", businessType = BusinessType.GEN_CODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String[] tableNames) throws IOException {
        byte[] data = genService.generatorCode(tableNames);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"novel.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
